<style>

</style>

<template>
  <p>
    <a-space>
        <TrainSelectView v-model:value="queryParam.code" width="200px"></TrainSelectView>
        <a-date-picker v-model:value="queryParam.date" valueFormat="YYYY-MM-DD" placeholder="请选择日期" :disabled="!!dailyTrain.id"/>
        <a-button type="primary" @click="handleQuery()">查询</a-button>
        <a-button type="primary" @click="handleQuery()">刷新</a-button>
        <a-button type="primary" @click="onAdd">新增</a-button>
        <a-button type="primary" danger @click="onGenDailyTrain" >手动生成车次信息</a-button>
    </a-space>
    </p>
    <a-table 
        :dataSource="dailyTrains" 
        :columns="columns" 
        :pagination="pagination" 
        :loading="loading"
        @change="handleTableChange" 
    >
        <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'operation'">
                <a-space>
                    <a-popconfirm
                        title="删除后不可恢复，确认删除?"
                        @confirm="onDelete(record)"
                        ok-text="确认"
                        cancel-text="取消"
                    >
                        <a style="color: red">删除</a>
                    </a-popconfirm>
                
                    <a @click="onEdit(record)">编辑</a>
                </a-space>
            </template>
        </template>
    </a-table>
    <a-modal v-model:visible="visible" title="火车车次" @ok="handleOk" ok-text="确认" cancel-text="取消">
        <a-form :model="dailyTrain" :label-col="{span: 4}" :wrapper-col="{span: 14}">
            <a-form-item label="日期">
                <!-- :disabled="!!dailyTrain.date"设置编辑的时候火车日期不可修改 -->
                <a-date-picker v-model:value="dailyTrain.date" valueFormat="YYYY-MM-DD" placeholder="请选择日期" :disabled="!!dailyTrain.id"/>
            </a-form-item>
            <a-form-item label="火车编号">
                <TrainSelectView v-model="dailyTrain.code" @change="onChangeCode" />
                <!-- :disabled="!!dailyTrain.id"设置编辑的时候火车编号不可修改 -->
                <!-- <a-input v-model:value="dailyTrain.code" :disabled="!!dailyTrain.id"/> -->
            </a-form-item>
            <a-form-item label="车次类型">
                <a-select v-model:value="dailyTrain.type">
                    <!-- <a-select-option v-for="(item,index) in passengerTypeEnums" :key="index + 1" >{{item.desc}}</a-select-option> -->
                    <a-select-option value="G">高铁</a-select-option>
                    <a-select-option value="D">动车</a-select-option>
                    <a-select-option value="K">快速</a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item label="始发站">
              <StationSelectView v-model:value="dailyTrain.start"></StationSelectView>
            </a-form-item>
            <a-form-item label="始发站拼音">
              <a-input v-model:value="dailyTrain.startPinyin" disabled/>
            </a-form-item>
            <a-form-item label="出发时间">
              <a-time-picker v-model:value="dailyTrain.startTime" valueFormat="HH:mm:ss" placeholder="请选择时间"/>
            </a-form-item>
            <a-form-item label="终点站">
              <StationSelectView v-model:value="dailyTrain.end"></StationSelectView>
            </a-form-item>
            <a-form-item label="终点站拼音">
              <a-input v-model:value="dailyTrain.endPinyin" disabled/>
            </a-form-item>
            <a-form-item label="到站时间">
              <a-time-picker v-model:value="dailyTrain.endTime" valueFormat="HH:mm:ss" placeholder="请选择时间"/>
            </a-form-item>
        </a-form>
    </a-modal>
    <a-modal v-model:visible="genDailyVisible" title="生成车次" @ok="handleGenDailyOk"
           :confirm-loading="genDailyLoading" ok-text="确认" cancel-text="取消">
        <a-form :model="genDaily" :label-col="{span: 4}" :wrapper-col="{ span: 20 }">
            <a-form-item label="日期">
                <a-date-picker v-model:value="genDaily.date" valueFormat="YYYY-MM-DD" placeholder="请选择日期"/>
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script>
import { defineComponent,ref,onMounted,watch} from 'vue';
import { notification } from 'ant-design-vue';
import {pinyin} from 'pinyin-pro'
import axios from 'axios';
import TrainSelectView from '@/components/TrainSelectView.vue';
import StationSelectView from '@/components/StationSelectView.vue';
import dayjs from 'dayjs';

export default defineComponent({
    name: "dailyTrain-view",
    components: { 
        StationSelectView,
        TrainSelectView
    },
    setup() {
        // 展示模态窗的标签的定义
        const visible = ref(false);
        const loading = ref(false);
        const genDailyVisible = ref(false);
        const genDailyLoading = ref(false);

        const queryParam = ref({
            date: null,
            code: null
        })

        const genDaily = ref({
            date: null
        });

        // 定义车站对象
        let dailyTrain = ref({
            id: undefined,
            date: undefined,
            code: undefined,
            type: undefined,
            start: undefined,
            startPinyin: undefined,
            startTime: undefined,
            end: undefined,
            endPinyin: undefined,
            endTime: undefined,
            createTime: undefined,
            updateTime: undefined
        });

        const dailyTrains = ref([]);
        
        const columns = [
            {
                title: '日期',
                dataIndex: 'date',
                key: 'date',
            },
            {
                title: '车次编号',
                dataIndex: 'code',
                key: 'code',
            },
            {
                title: '车次类型',
                dataIndex: 'type',
                key: 'type',
            },
            {
                title: '始发站',
                dataIndex: 'start',
                key: 'start',
            },
            {
                title: '始发站拼音',
                dataIndex: 'startPinyin',
                key: 'startPinyin',
            },
            {
                title: '出发时间',
                dataIndex: 'startTime',
                key: 'startTime',
            },
            {
                title: '终点站',
                dataIndex: 'end',
                key: 'end',
            },
            {
                title: '终点站拼音',
                dataIndex: 'endPinyin',
                key: 'endPinyin',
            },
            {
                title: '到站时间',
                dataIndex: 'endTime',
                key: 'endTime',
            },
            {
                title: '操作',
                dataIndex: 'operation',
                key: 'operation',
            }
        ];

        let pagination = ref({
            total: 0,
            current: 1,
            pageSize: 10,
        });

        // 点击新增展示模态窗的函数方法
        const onAdd = () => {
            console.log("add");
            visible.value = true;
            dailyTrain.value = {};
        };

        // 点击编辑展示模态窗的函数方法
        const onEdit = (record) => {
            console.log("edit");
            dailyTrain.value = window.Tool.copy(record);
            visible.value = true;
        };

        // 点击删除按钮的函数方法
        const onDelete = (record) => {
            axios.delete("/business/admin/daily-train/delete/" + record.id)
                .then(response => {
                console.log(response.data.data);
                if (response.data.data) {
                    notification.success({ description: '删除成功' });
                    // 刷新页面
                    handleQuery();
                }
            })
                .catch(error => {
                notification.error({ description: error.response.data.data });
            });
        };

        // 点击生成座位按钮的函数方法
        const generatorSeat = (record) => {
            axios.get("/business/admin/daily-train/generate-seat/" + record.code)
            .then(response => {
                notification.success({ description: '座位生成成功' });
                // 刷新页面
                handleQuery();
            })
            .catch(error => {
                notification.error({ description: "生成失败" });
            });
        };

        // 手动生成每日车次信息
        const onGenDailyTrain = (record) => {
            genDailyVisible.value = true;
        };

        const handleGenDailyOk = () => {
            let date = dayjs(genDaily.value.date).format("YYYY-MM-DD");
            genDailyLoading.value = true;
            axios.get("/business/admin/daily-train/gen-daily/" + date)
                .then(response => {
                    console.log(response)
                    genDailyLoading.value = false;
                    notification.success({description: "生成成功！"});
                    genDailyVisible.value = false;
                    handleQuery({
                        page: pagination.value.current,
                        size: pagination.value.pageSize
                    });
                })
                .catch(error => {
                    console.log(error)
                    alert("错误")
                });
        };

        // 点击模态窗的ok按钮执行的函数方法
        const handleOk = e => {
            switch (dailyTrain.value.type) {
                case "高铁":
                    dailyTrain.value.type = "G"
                    break;
                case "快速":
                    dailyTrain.value.type = "K"
                    break;
                case "动车":
                    dailyTrain.value.type = "D"
                    break;
                default:
                    break;
            }
            axios.post("/business/admin/daily-train/save", dailyTrain.value)
                .then(response => {
                let respData = response.data;
                console.log(respData);
                if (respData.data) {
                    notification.success({ description: '保存成功！' });
                    // 设置为false，关闭模态窗
                    visible.value = false;
                    // 调用列表查询的接口，刷新数据
                    handleQuery();
                }
                else {
                    notification.error({ description: respData.errorMessage });
                }
            })
                .catch(error => {
                let errData = error.response.data;
                console.log(errData);
                notification.error({ description: errData.data });
            });
        };

        // 车站信息列表查询的方法
        const handleQuery = e => {
            // 刷新时候不带参数的判断
            if (!e) {
                e = {
                    page: 1,
                    limit: pagination.value.pageSize
                };
            }
            // 开启loading效果
            loading.value = true;
            axios.get("/business/admin/daily-train/query", {
                params: {
                    page: e.page,
                    limit: e.limit,
                    date: queryParam.value.date,
                    code: queryParam.value.code
                }
            })
                .then(response => {
                // 关闭loading效果
                loading.value = false;
                let respData = response.data;
                let trainDataList = respData.data.dataList;
                // 对火车类型进行转换
                trainDataList.forEach(dailyTrain => {
                    switch (dailyTrain.type) {
                        case "K":
                            dailyTrain.type = "快速";
                            break;
                        case "D":
                            dailyTrain.type = "动车";
                            break;
                        case "G":
                            dailyTrain.type = "高铁";
                            break;
                        default:
                            dailyTrain.type = "其他";
                            break;
                    }
                });
                dailyTrains.value = trainDataList;
                // 分页控件的设置
                let total = respData.data.total;
                let currentPage = respData.data.currentPage;
                let pageSize = respData.data.pageSize;
                pagination.value.total = total;
                pagination.value.current = currentPage;
                pagination.value.pageSize = pageSize;
            })
                .catch(error => {
                // 关闭loading效果
                loading.value = false;
                let errData = error.response.data;
                console.log(errData);
                notification.error({ description: errData.data });
            });
        };

        // 页码的点击事件
        const handleTableChange = (pagination) => {
            console.log("pagination:", pagination.value);
            // 调用车站列表查询方法
            handleQuery({
                page: pagination.current,
                limit: pagination.pageSize
            });
        };

        const onChangeCode = (train) => {
            console.log("车次下拉组件选择：", train);
            let t = window.Tool.copy(train);
            delete t.id;
            // 用assign可以合并
            dailyTrain.value = Object.assign(dailyTrain.value, t);
        };

        // 钩子函数，页面初始化的时候执行
        onMounted(() => {
            handleQuery({
                page: pagination.value.current,
                limit: pagination.value.pageSize
            });
        });

        // watch计算函数监听name属性的变化
        watch(() => dailyTrain.value.start, () => {
            if (window.Tool.isNotEmpty(dailyTrain.value.start)) {
                dailyTrain.value.startPinyin = pinyin(dailyTrain.value.start, { toneType: 'none' }).replaceAll(" ", "");
            }
            else {
                dailyTrain.value.startPinyin = "";
            }
        }, { immediate: true });
        watch(() => dailyTrain.value.end, () => {
            if (window.Tool.isNotEmpty(dailyTrain.value.end)) {
                dailyTrain.value.endPinyin = pinyin(dailyTrain.value.end, { toneType: 'none' }).replaceAll(" ", "");
            }
            else {
                dailyTrain.value.endPinyin = "";
            }
        }, { immediate: true });

        return {
            visible,
            loading,
            genDailyVisible,
            genDailyLoading,
            queryParam,
            genDaily,
            dailyTrain,
            dailyTrains,
            columns,
            pagination,
            onAdd,
            onEdit,
            onDelete,
            onChangeCode,
            generatorSeat,
            onGenDailyTrain,
            handleGenDailyOk,
            handleOk,
            handleQuery,
            handleTableChange
        };
    },
});
</script>